package com.salt.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.salt.common.Result;
import com.salt.dto.PromotionLinkRequest;
import com.salt.entity.IdleAffiliateMaterial;
import com.salt.entity.MaterialQueryRequest;
import com.salt.service.IdleAffiliateMaterialService;
import com.salt.service.TaobaoApiService;
import com.taobao.api.response.AlibabaIdleAffiliateMaterialExactGetResponse;
import com.taobao.api.response.AlibabaIdleAffiliateMaterialQueryResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 闲鱼联盟物料信息控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/material")
@RequiredArgsConstructor
public class IdleAffiliateMaterialController {

    private final IdleAffiliateMaterialService materialService;
    private final TaobaoApiService taobaoApiService;


    @PostMapping("/materials")
    public Result<List<AlibabaIdleAffiliateMaterialQueryResponse.AffiliateActivityPage>> queryMaterials(
            @RequestBody MaterialQueryRequest request
    ) {
        try {
            AlibabaIdleAffiliateMaterialQueryResponse alibabaIdleAffiliateMaterialQueryResponse = taobaoApiService.queryMaterials(
                    request.getMaterialType(),
                    request.getPageSize(),
                    request.getPageNum(),
                    request.getTabName(),
                    request.getItemPublisherTime(),
                    request.getSellerCreditLevel(),
                    request.getFilterLevel5Yxp(),
                    request.getFilterYhb(),
                    request.getSellerName(),
                    request.getKeyword()
            );
            List<AlibabaIdleAffiliateMaterialQueryResponse.MaterialDTO> result = alibabaIdleAffiliateMaterialQueryResponse.getResult().getResult();

            List<AlibabaIdleAffiliateMaterialQueryResponse.AffiliateActivityPage> activityPageInfoList = new ArrayList<>();
            for (AlibabaIdleAffiliateMaterialQueryResponse.MaterialDTO materialDTO : result) {
                if (materialDTO.getActivityPageInfo() != null) {
                    activityPageInfoList.add(materialDTO.getActivityPageInfo());
                }
            }
            return Result.success(activityPageInfoList);
        } catch (Exception e) {
            log.error("查询闲鱼联盟物料失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询物料信息
     */
    @GetMapping("/page")
    public Result<Page<IdleAffiliateMaterial>> page(
        @RequestParam(defaultValue = "1") long current,
        @RequestParam(defaultValue = "10") long size,
        @RequestParam(required = false) String categoryName,
        @RequestParam(required = false) String status
    ) {
        try {
            // 创建分页对象
            Page<IdleAffiliateMaterial> page = new Page<>(current, size);
            
            // 执行分页查询
            Page<IdleAffiliateMaterial> pageResult = materialService.page(page, categoryName, status);
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询物料信息失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据商品ID查询物料信息
     */
    @GetMapping("/itemId")
    public Result<IdleAffiliateMaterial> getByItemId(@RequestParam String id) {
        try {
            IdleAffiliateMaterial material = materialService.getById(id);
            return Result.success(material);
        } catch (Exception e) {
            log.error("查询物料信息失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据商品ID获取并保存物料信息
     */
    @PostMapping("/sync/itemId")
    public Result<AlibabaIdleAffiliateMaterialExactGetResponse> syncMaterial(
        @RequestBody PromotionLinkRequest request
    ) {
        try {
            // URL decode the itemId to handle special characters
            String decodedItemId = java.net.URLDecoder.decode(request.getItemId(), java.nio.charset.StandardCharsets.UTF_8.name());
            AlibabaIdleAffiliateMaterialExactGetResponse andSaveMaterial = taobaoApiService.getAndSaveMaterial(request.getItemId());
            if (andSaveMaterial == null) {
                return Result.error("获取物料信息失败");
            }
            return Result.success(andSaveMaterial);
        } catch (Exception e) {
            log.error("同步物料信息失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 生成推广链接
     *
     * @param request 推广链接请求参数
     * @return 推广链接信息
     */
    @PostMapping("/promotion-link")
    public Result<?> generatePromotionLink(@RequestBody PromotionLinkRequest request) {
        try {
            return Result.success(taobaoApiService.generatePromotionLink(request.getItemId(), request.getMaterialType()));
        } catch (Exception e) {
            log.error("生成推广链接失败", e);
            return Result.error(e.getMessage());
        }
    }



    /**
     * 生成推广链接
     *
     * @param request 推广链接请求参数
     * @return 推广链接信息
     */
    @PostMapping("/promotion-link-new")
    public Result<?> generatePromotionLinkNew(@RequestBody PromotionLinkRequest request) {
        try {
            return Result.success(taobaoApiService.generatePromotionLink(request.getItemId(), request.getMaterialType()));
        } catch (Exception e) {
            log.error("生成推广链接失败", e);
            return Result.error(e.getMessage());
        }
    }
} 